package com.yhy.wxzn.wcs.device.scanner.handler;

import com.yhy.wxzn.wcs.device.scanner.BarcodeScannerClient;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Setter
@Getter
public class BarcodeScannerClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private volatile String barCode = "";
    private volatile boolean haveMessage;

    /**
     * 连接
     */
    private volatile boolean connected;




    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);
        String resStr = "";
        if (bytes.length < 2 || bytes[0] != BarcodeScannerClient.STX) return;

        if (bytes[1] != BarcodeScannerClient.CAN)  resStr = new String(bytes,1,bytes.length - 3);

        this.barCode = resStr;
        this.haveMessage = true;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        connected = true;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        connected = false;
    }


    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        connected = false;
    }


    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        connected = false;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        connected = false;
    }
}

